package com.collabscm.tools.ant;

import org.apache.tools.ant.types.FilterSet;

/**
 * 国际化的过滤，参考ant已有的FilterSet的实现。
 * @see org.apache.tools.ant.types.FilterSet
 * @author Zeng Raoxing
 */
public class I18nFilterSet extends FilterSet {
	/**
	 * 是否仅将beginToken和endToken删除，保持内容不变。
	 */
	private boolean isTrimToken;

	public boolean isTrimToken() {
		return isTrimToken;
	}

	public void setTrimToken(boolean isTrimToken) {
		this.isTrimToken = isTrimToken;
	}

	@Override
	/**
	 * 替换token中的内容
	 */
	public synchronized String replaceTokens(String line) {
		if(isTrimToken) {
			return trimTokens(line);
		} else {
			return line;
		}
	}

	/**
	 * 仅删除token的标识保留token的内容
	 * @param line
	 */
    private synchronized String trimTokens(String line) {
        String beginToken = getBeginToken();
        String endToken = getEndToken();
        int index = line.indexOf(beginToken);

        if (index > -1) {
            try {
                StringBuffer b = new StringBuffer();
                int i = 0;
                String token = null;

                while (index > -1) {
                    //can't have zero-length token
                    int endIndex = line.indexOf(endToken,
                        index + beginToken.length() + 1);
                    if (endIndex == -1) {
                        break;
                    }
                    token
                        = line.substring(index + beginToken.length(), endIndex);
                    b.append(line.substring(i, index)).append(token);
                    i = index + beginToken.length() + token.length()
                            + endToken.length();
                    index = line.indexOf(beginToken, i);
                }

                b.append(line.substring(i));
                return b.toString();
            } catch (StringIndexOutOfBoundsException e) {
                return line;
            }
        } else {
           return line;
        }
    }
	
}
